<?php
error_reporting(-1);
ini_set('display_errors', 1);

date_default_timezone_set('Asia/Ho_Chi_Minh');

require APPPATH . "libraries/simple_html_dom.php";

class admin_video extends CI_Controller {

    protected $_page_id = 'ul_postcontainer';
    protected $_page_name = "admin_video";
    protected $data; //data for this page.
    protected $_page_title = ADMINTITLE_VIDEO;
    protected $_base_url;
    protected $folder_save_video_image = "style/upimg_man/image/video/";
    protected $news_get_count;
    protected $returnCode;
    protected $news_lastest_url;
    protected $flag_check_lastest_news;
    protected $flag_check_update;

    function __construct() {
        $this->_initdata();
    }

    function index() {
        $this->load_video_list();
        $this->showadmin($this->data);
    }

    function load_video_list() {
        $iCurPage = $this->uri->segment(2);
        if ($iCurPage < 1) {
            $iCurPage = 1;
        }
        
        @$limit = PAGESIZE;
        $start = $iCurPage * PAGESIZE - PAGESIZE;
        if (!($start > 0)) {
            $start = 0;
        }

        if (!$limit > 0) {
            $limit = 20;
        }
        list($this->data['videoCount'], $this->data['aVideos']) = $this->_get_video_from_db($start, $limit);
        $iRow_Count = $this->data['videoCount'];
        $this->data['paging'] = $this->paging($iCurPage, ceil($iRow_Count / PAGESIZE), $this->config->item('base_url') . $this->_page_name, $iRow_Count);
        $this->data['cur_page'] = $iCurPage;
        $this->data['previous_id'] = 1;
    }
    
    //delete video
    function delete(){
        $videoId = $this->uri->segment(3);
        $result = $this->Adminmodel->deleteVideo($videoId);
        
        if($result == 1){
            echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><script type='text/javascript'>alert('Xóa video có id=" . $videoId . " thành công');</script>";
            echo "<script>window.location.href='/admin_video'</script>";
        }
        else{
            echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><script type='text/javascript'>alert('Xóa video có id=" . $videoId . " KHÔNG thành công');</script>";
            echo "<script>window.location.href='/admin_video'</script>";
        }
    }
    
    //get video from Youtube
    function get_video(){
        $urlLastestResult = $this->Adminmodel->getLastestVideo();
        $urlLastest = $urlLastestResult == null ? "" : $urlLastestResult[0]->link;
        $countGetVideo = 0;
        
        $urlYoutube = "https://www.youtube.com/channel/UCJ6dRTULWJnc1bkmNRJ15Cw/videos?flow=grid&view=0&sort=dd";
        $item_tag = "li[class=channels-content-item yt-shelf-grid-item]";
        $image_tag = "img";
        $title_tag = "a";
        $url_tag = "a";
        
        $html = file_get_html($urlYoutube);
        $items = $html->find($item_tag);
        
        $data = array();
        
        foreach($items as $item){
            $video_temp = $item->find($url_tag);
            $video_url = $video_temp[0]->href;
            $temp1 = explode("=", $video_url, 2);
            $temp2 = explode("&", $temp1[1], 2);
            $video_id_youtube = $temp2[0];
            
            if(strcmp($video_id_youtube, $urlLastest) == 0){
                break;
            }
            
            $video_img = $item->find($image_tag);
            $video_title = $item->find($title_tag);
            
            $data[$countGetVideo]["link"] = $video_id_youtube;
            $data[$countGetVideo]["img"] = $video_img[0]->src;
            $data[$countGetVideo]["title"] = $video_title[1]->title;
            
            $countGetVideo++;
        }
        
        $insert_result = 0;
        if($countGetVideo > 0){
            $insert_result = $this->Adminmodel->_insert_video_to_db($data);
        }
        
        if($insert_result == 1){
            echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><script type='text/javascript'>alert('Đã thêm " . $countGetVideo . " video thành công');</script>";
            echo "<script>window.location.href='/admin_video'</script>";
        }
        else{
            echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><script type='text/javascript'>alert('KHÔNG có video mới được thêm vào.');</script>";
            echo "<script>window.location.href='/admin_video'</script>";
        }
        
    }

    //local func
    function paging($page, $totalpage, $pagelink, $totalrows) {
        $paging_str = '';
        $paging_str .= 'Trang: &nbsp;&nbsp;&nbsp;';
        if ($page > 1)
            $paging_str .= '<img src="' . $this->config->item('base_url') . 'style/img/img21_arrow_left.gif" align="absmiddle" style="cursor:pointer;" onclick="location.href=' . "'" . $pagelink . '/' . ($page - 1) . "'" . '">';
        else
            $paging_str .= '<img src="' . $this->config->item('base_url') . 'style/img/img21_arrow_left.gif" align="absmiddle">';
        $paging_str .= '&nbsp;&nbsp;&nbsp;';

        // list 10 pagelink
        $startpage = 1;
        if ($page > 5)
            $startpage = $page - 4;
        $endpage = $totalpage;
        if ($totalpage - $page > 5)
            $endpage = $page + 5;
        for ($i = $startpage; $i < $page; $i++)
            $paging_str .= ' <a href="' . $pagelink . '/' . $i . '" class="link">' . $i . '</a>';
        $paging_str .= ' <a href="' . $pagelink . '/' . $i . '" class="link_selected">' . $page . '</a>';
        for ($i = $page + 1; $i <= $endpage; $i++)
            $paging_str .= ' <a href="' . $pagelink . '/' . $i . '" class="link">' . $i . '</a>';

        $paging_str .= '&nbsp;&nbsp;&nbsp;';
        if ($page < $totalpage)
            $paging_str .= '<img src="' . $this->config->item('base_url') . 'style/img/img22_arrow_right.gif" align="absmiddle" style="cursor:pointer;" onclick="location.href=' . "'" . $pagelink . '/' . ($page + 1) . "'" . '">';
        else
            $paging_str .= '<img src="' . $this->config->item('base_url') . 'style/img/img22_arrow_right.gif" align="absmiddle">';
        $paging_str .= '&nbsp;&nbsp;&nbsp;</span></td>';

        $paging_str .= '&nbsp;&nbsp;&nbsp;<span class="paging_total"><strong>[ </strong>T&#7893;ng c&#7897;ng: <font color="Red">' . $totalrows . '</font> k&#7871;t qu&#7843; <strong> ]</strong></span>';
        return $paging_str;
    }

    function _initdata() {
        parent::__construct();
        session_start();
		set_time_limit(0);
        $this->load->model('Adminmodel');
        $this->load->helper('url');
        $this->_check_admin_login();

        //init data (this page, header admin)

        $this->data['static_url'] = $this->config->item('img_url');
        $this->data['base_url'] = $this->config->item('base_url');
        $this->data['page_title'] = $this->_page_title;
        $this->data['admintitle_news'] = ADMINTITLE_NEWS;
        $this->data['admintitle_news_auto'] = ADMINTITLE_NEWS_AUTO;
        $this->data['admintitle_video'] = ADMINTITLE_VIDEO;
        $this->data['admintitle_customs'] = ADMINTITLE_CUSTOMS;
        $this->data['admintitle_adv'] = ADMINTITLE_ADV;
        $this->data['admintitle_faq'] = ADMINTITLE_FAQ;
        $this->data['admintitle_contact'] = ADMINTITLE_CONTACT;
        $this->data['admintitle_common'] = ADMINTITLE_COMMON;
        $this->data['admintitle_stats'] = ADMINTITLE_STATS;
        $this->data['admintitle_beuser'] = ADMINTITLE_BEUSER;
        $this->data['website_name'] = WEBSITE_NAME;
        $this->data['link_page_name'] = $this->_page_name;
        $this->data['is_addnew'] = ""; //show link add
        $this->data['is_addlist'] = "NOT_SHOW"; //show link list
        $this->data['is_news_auto'] = ""; //show button get news auto
        $this->data['page_id'] = $this->_page_id;
        $this->data['page_name'] = $this->_page_name;
        $this->news_get_count = 0;
    }

    function _check_admin_login() {
        if (($this->Adminmodel->_check_login(SESSION_ADMINUSERNAME) == false) ||
                (time() - $this->Adminmodel->_get_session(SESSION_ADMINTIMEOUT)) > SESSION_ADMINTIMEOUTVALUE) {
            $base_url = $this->config->item('base_url');
            redirect($base_url . 'admin_login', 'location', 301);
        } else
            $this->Adminmodel->_set_session(SESSION_ADMINTIMEOUT, time());
    }

    //Hiển thi tin tức từ DB
    function _get_video_from_db($page_index, $page_size) {
        return $this->Adminmodel->_get_video_from_db($page_index, $page_size);
    }

}

?>
